//
//  UICollectionView+Extension.swift
//  Lease_IOS
//
//  Created by Mr.wang on 2018/12/26.
//  Copyright © 2018 Mr.wang. All rights reserved.
//

import UIKit
import RxSwift
import RxDataSources
import RxCocoa

extension UICollectionView {
    
    func autoSelect(at indexPath: IndexPath) {
        self.rx.methodInvoked(#selector(reloadData))
            .bind{ [weak self] _ in
                guard let self = self,
                    indexPath.section < self.numberOfSections,
                    indexPath.item < self.numberOfItems(inSection: indexPath.section),
                    self.indexPathsForSelectedItems == nil else { return }
                self.selectItem(at: indexPath, animated: true
                    , scrollPosition: .left)
            }.disposed(by: rx.disposeBag)
    }
    
    func register<Cell: UICollectionViewCell>(_ cellType: Cell.Type) {
        register(cellType, forCellWithReuseIdentifier: Cell.reuseIdentifier)
    }
    
    func dequeueReusableCell<Cell: UICollectionViewCell>(_ cellType: Cell.Type, for indexPath: IndexPath) -> Cell {
        guard let cell = dequeueReusableCell(withReuseIdentifier: Cell.reuseIdentifier, for: indexPath) as? Cell else {
            fatalError("tableview没有注册cell")
        }
        return cell
    }
    
}

extension Reactive where Base: UICollectionView {
    
    public func items<S: Sequence, Cell: UICollectionViewCell, O : ObservableType>
        (cellType: Cell.Type = Cell.self)
        -> (_ source: O)
        -> (_ configureCell: @escaping (Int, S.Iterator.Element, Cell) -> Void)
        -> Disposable
        where O.Element == S {
            return self.items(cellIdentifier: Cell.reuseIdentifier, cellType: cellType)
    }
    
}
